<template>
  <view class="comment-container">
    <!-- 评论列表 -->
    <scroll-view
      class="comment-list"
      scroll-y
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 评论总数 -->
      <view class="comment-count">
        <text class="count-text">{{ total }}条评论</text>
      </view>

      <!-- 评论项 -->
      <view class="comment-item" v-for="item in commentList" :key="item.id">
        <view class="comment-header">
          <view class="user-info">
            <u-avatar :src="item.avatar || '/static/images/default-avatar.png'" size="40"></u-avatar>
            <view class="user-details">
              <text class="username">{{ item.nickName || '用户' + item.uid }}</text>
              <text class="comment-time">{{ formatTime(item.createTime) }}</text>
            </view>
          </view>
          <view class="comment-actions">
            <u-icon name="more-dot-fill" color="#999" size="20" @click="showActionSheet(item)"></u-icon>
          </view>
        </view>

        <view class="comment-content">
          <text class="comment-text">{{ item.content }}</text>
        </view>

        <view class="comment-footer">
          <view class="interaction-buttons">
            <view class="interaction-btn" @click="handleLike(item)">
              <u-icon
                :name="item.isLiked ? 'thumb-up-fill' : 'thumb-up'"
                :color="item.isLiked ? '#4facfe' : '#999'"
                size="18"
              ></u-icon>
              <text class="btn-text">{{ item.likeCount || 0 }}</text>
            </view>
            <view class="interaction-btn" @click="handleReply(item)">
              <u-icon name="chat" color="#999" size="18"></u-icon>
              <text class="btn-text">回复</text>
            </view>
          </view>
        </view>

        <!-- 回复列表 -->
        <view class="reply-list" v-if="item.replyCount > 0">
          <view class="reply-item" v-for="(reply, index) in item.replies" :key="reply.id">
            <view class="reply-user">
              <text class="reply-username">{{ reply.nickName || '用户' + reply.uid }}</text>
              <text v-if="reply.toUid" class="reply-to">回复</text>
              <text v-if="reply.toUid" class="reply-to-username">{{ reply.toNickName || '用户' + reply.toUid }}</text>
              <text class="reply-text">: {{ reply.content }}</text>
            </view>
          </view>
          <view class="view-more" v-if="item.replyCount > 3" @click="viewMoreReplies(item)">
            <text class="view-more-text">查看全部{{ item.replyCount }}条回复</text>
            <u-icon name="arrow-right" color="#999" size="14"></u-icon>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <u-loading-icon v-if="loading" color="#4facfe" size="20"></u-loading-icon>
        <text class="load-text">{{ loading ? '加载中...' : '上拉加载更多' }}</text>
      </view>

      <!-- 没有更多数据 -->
      <view class="no-more" v-if="!hasMore && commentList.length > 0">
        <text class="no-more-text">没有更多评论了</text>
      </view>

      <!-- 暂无评论 -->
      <view class="empty-comment" v-if="!loading && commentList.length === 0">
        <u-icon name="chat" color="#999" size="50"></u-icon>
        <text class="empty-text">暂无评论，快来抢沙发吧~</text>
      </view>
    </scroll-view>

    <!-- 评论输入框 -->
    <view class="comment-input-container">
      <view class="input-wrapper">
        <input
          class="comment-input"
          v-model="commentContent"
          placeholder="说点什么..."
          :focus="inputFocus"
          @blur="inputFocus = false"
          @confirm="submitComment"
        />
        <button class="send-btn" :disabled="!commentContent.trim()" @click="submitComment">发送</button>
      </view>
    </view>

    <!-- 操作菜单 -->
    <u-action-sheet
      :show="showActions"
      :actions="actionOptions"
      @close="showActions = false"
      @select="handleActionSelect"
    ></u-action-sheet>
  </view>
</template>

<script>
import { isLoggedIn } from '@/utils/auth'
import commentApi from '@/api/quanzi/comment'

export default {
  data() {
    return {
      postId: null,
      refreshing: false,
      loading: false,
      hasMore: true,
      page: 1,
      pageSize: 10,
      total: 0,
      commentList: [],
      commentContent: '',
      inputFocus: false,
      replyToComment: null,
      showActions: false,
      actionOptions: [],
      currentComment: null,
      isUserLoggedIn: false
    }
  },

  onLoad(options) {
    this.postId = options.id
    this.checkUserLoginStatus()
    this.loadComments()
  },

  methods: {
    // 检查用户登录状态
    checkUserLoginStatus() {
      this.isUserLoggedIn = isLoggedIn()
    },

    // 加载评论列表
    async loadComments() {
      if (this.loading) return

      this.loading = true

      try {
        const res = await commentApi.listPostComments(this.postId, {
          pageNum: this.page,
          pageSize: this.pageSize,
          postId: this.postId
        })

        if (res.code === 200) {
          const comments = res.rows || []
          this.total = res.total || 0
          
          if (this.page === 1) {
            this.commentList = comments
          } else {
            this.commentList.push(...comments)
          }
          
          this.hasMore = comments.length === this.pageSize
        } else {
          this.showToast(res.msg || '加载评论失败', 'error')
        }
      } catch (error) {
        console.error('加载评论失败:', error)
        this.showToast('网络错误，请重试', 'error')
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },

    // 下拉刷新
    async onRefresh() {
      this.page = 1
      this.hasMore = true
      await this.loadComments()
    },

    // 加载更多
    async loadMore() {
      if (this.loading || !this.hasMore) return
      this.page++
      await this.loadComments()
    },

    // 提交评论
    async submitComment() {
      if (!this.commentContent.trim()) return
      
      if (!this.isUserLoggedIn) {
        this.showLoginTip('发表评论')
        return
      }

      try {
        const data = {
          content: this.commentContent
        }

        if (this.replyToComment) {
          data.pid = this.replyToComment.id
          data.toUid = this.replyToComment.uid
        }

        const res = await commentApi.createComment(this.postId, data)

        if (res.code === 200) {
          this.showToast('评论成功', 'success')
          this.commentContent = ''
          this.replyToComment = null
          this.page = 1
          this.loadComments()
        } else {
          this.showToast(res.msg || '评论失败', 'error')
        }
      } catch (error) {
        console.error('评论失败:', error)
        this.showToast('网络错误，请重试', 'error')
      }
    },

    // 点赞评论
    async handleLike(comment) {
      if (!this.isUserLoggedIn) {
        this.showLoginTip('点赞评论')
        return
      }

      try {
        let res
        if (comment.isLiked) {
          res = await commentApi.unlikeComment(comment.id)
        } else {
          res = await commentApi.likeComment(comment.id)
        }

        if (res.code === 200) {
          comment.isLiked = !comment.isLiked
          comment.likeCount = comment.isLiked 
            ? (comment.likeCount || 0) + 1 
            : Math.max(0, (comment.likeCount || 0) - 1)
          this.showToast(comment.isLiked ? '点赞成功' : '取消点赞', 'success')
        } else {
          this.showToast(res.msg || '操作失败', 'error')
        }
      } catch (error) {
        console.error('点赞失败:', error)
        this.showToast('网络错误，请重试', 'error')
      }
    },

    // 回复评论
    handleReply(comment) {
      if (!this.isUserLoggedIn) {
        this.showLoginTip('回复评论')
        return
      }

      this.replyToComment = comment
      this.commentContent = ''
      this.inputFocus = true
    },

    // 显示操作菜单
    showActionSheet(comment) {
      this.currentComment = comment
      const isOwner = this.isUserLoggedIn && comment.uid === this.$store.getters.userId

      this.actionOptions = []
      
      if (isOwner) {
        this.actionOptions.push({
          text: '删除',
          color: '#ff4757'
        })
      }
      
      this.actionOptions.push({
        text: '举报',
        color: '#333'
      })

      if (this.actionOptions.length > 0) {
        this.showActions = true
      }
    },

    // 处理操作选择
    async handleActionSelect(index) {
      const action = this.actionOptions[index]
      if (!this.currentComment) return

      if (action.text === '删除') {
        this.deleteComment(this.currentComment)
      } else if (action.text === '举报') {
        this.reportComment(this.currentComment)
      }
    },

    // 删除评论
    async deleteComment(comment) {
      try {
        const res = await commentApi.deleteComment(comment.id)
        if (res.code === 200) {
          this.showToast('删除成功', 'success')
          const index = this.commentList.findIndex(item => item.id === comment.id)
          if (index !== -1) {
            this.commentList.splice(index, 1)
            this.total--
          }
        } else {
          this.showToast(res.msg || '删除失败', 'error')
        }
      } catch (error) {
        console.error('删除评论失败:', error)
        this.showToast('网络错误，请重试', 'error')
      }
    },

    // 举报评论
    reportComment(comment) {
      uni.showModal({
        title: '举报评论',
        content: '确定要举报这条评论吗？',
        success: (res) => {
          if (res.confirm) {
            this.showToast('举报成功，平台将尽快处理', 'success')
          }
        }
      })
    },

    // 查看更多回复
    viewMoreReplies(comment) {
      uni.navigateTo({
        url: `/pages/post/reply?commentId=${comment.id}&postId=${this.postId}`
      })
    },

    // 显示登录提示
    showLoginTip(action = '此操作') {
      uni.showModal({
        title: '提示',
        content: `${action}需要登录，是否前往登录？`,
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login'
            })
          }
        }
      })
    },

    // 格式化时间
    formatTime(timeStr) {
      const time = new Date(timeStr)
      const now = new Date()
      const diff = now - time

      if (diff < 60000) return '刚刚'
      if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
      if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
      if (diff < 604800000) return Math.floor(diff / 86400000) + '天前'

      return time.toLocaleDateString()
    },

    // 显示提示
    showToast(title, type = 'default') {
      uni.showToast({
        title: title,
        icon: type === 'success' ? 'success' : 'none',
        duration: 2000
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/theme.scss';

.comment-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f9fa;
}

.comment-list {
  flex: 1;
  padding: 15px;
  padding-bottom: 70px;
}

.comment-count {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ecf0f1;
}

.count-text {
  font-size: 16px;
  font-weight: bold;
  color: #2c3e50;
}

.comment-item {
  background: #ffffff;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 10px;
}

.username {
  font-size: 15px;
  font-weight: 600;
  color: #2c3e50;
}

.comment-time {
  font-size: 12px;
  color: #95a5a6;
  margin-top: 2px;
  display: block;
}

.comment-content {
  margin-bottom: 10px;
}

.comment-text {
  font-size: 15px;
  color: #34495e;
  line-height: 1.5;
}

.comment-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 10px;
}

.interaction-buttons {
  display: flex;
  gap: 20px;
}

.interaction-btn {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.btn-text {
  font-size: 14px;
  color: #7f8c8d;
  margin-left: 5px;
}

.reply-list {
  margin-top: 10px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
}

.reply-item {
  margin-bottom: 8px;
}

.reply-item:last-child {
  margin-bottom: 0;
}

.reply-user {
  font-size: 14px;
  line-height: 1.5;
}

.reply-username {
  color: #4facfe;
  font-weight: 500;
}

.reply-to {
  color: #7f8c8d;
  margin: 0 4px;
}

.reply-to-username {
  color: #4facfe;
  font-weight: 500;
}

.reply-text {
  color: #34495e;
}

.view-more {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
  padding-top: 8px;
  border-top: 1px solid #ecf0f1;
}

.view-more-text {
  font-size: 14px;
  color: #4facfe;
  margin-right: 5px;
}

.comment-input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding: 10px 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.input-wrapper {
  display: flex;
  align-items: center;
}

.comment-input {
  flex: 1;
  height: 40px;
  background: #f8f9fa;
  border: 1px solid #ecf0f1;
  border-radius: 20px;
  padding: 0 15px;
  font-size: 14px;
  color: #2c3e50;
}

.send-btn {
  width: 60px;
  height: 40px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #ffffff;
  border: none;
  border-radius: 20px;
  margin-left: 10px;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:disabled {
  background: #ecf0f1;
  color: #95a5a6;
}

.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}

.load-text {
  font-size: 14px;
  color: #95a5a6;
  margin-left: 8px;
}

.no-more {
  text-align: center;
  padding: 20px 0;
}

.no-more-text {
  font-size: 14px;
  color: #95a5a6;
}

.empty-comment {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.empty-text {
  font-size: 16px;
  color: #95a5a6;
  margin-top: 15px;
}
</style>